package com.FH.organization.flow_path;


import com.FH.organization.people.KamMemberResource;
import com.FH.organization.people.KamMemberShowDTO;
import com.FH.util.AccessDB;
import com.FH.util.ResultDTO;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/9/21.
 */


@Stateless
public class FlowPathDAOImpl extends AccessDB implements FlowPathDAO {


    /**
     * 查询
     *
     * @param search
     * @param page
     * @param size
     * @return
     */
    @Inject
    KamMemberResource kamMemberResource;

    @Override
    public ResultDTO getFlowPathInfo(String search, String page, String size) {


        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from flow_path where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

            if (json.has("flow_path_id")) {
                sql_w += " AND flow_path_id = '" + json.getString("flow_path_id") + "'";
            }
            if (json.has("apply_manage_id")) {
                sql_w += " AND apply_manage_id = '" + json.getString("apply_manage_id") + "'";
            }

            if (json.has("not_pass")) {
                String nopass = json.getString("not_pass");
                if (nopass.equals("")) {
                    sql_w += " AND (not_pass IS NOT NULL)";
                } else {
                    sql_w += " AND not_pass = '" + json.getString("not_pass") + "'";
                }

            }

            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<FlowPathShowDTO> result = new ArrayList<FlowPathShowDTO>();
            if (!existName.equals("0")) {
                String sql = "select flow_path_id,apply_manage_id,member_id,organization_id,orderer,not_pass from flow_path where 1=1 " + sql_w + " ORDER BY orderer ASC" + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {

                    FlowPathShowDTO flowpath = new FlowPathShowDTO();
                    flowpath.setFlow_path_id(seresult.get(i)[1]);
                    flowpath.setApply_manage_id(seresult.get(i)[2]);
                    String member_id = seresult.get(i)[3];
                    flowpath.setMember_id(member_id);
                    flowpath.setOrganization_id(seresult.get(i)[4]);
                    flowpath.setOrderer(seresult.get(i)[5]);
                    String nopass = seresult.get(i)[6];
                    flowpath.setNot_pass(nopass);
                    ResultDTO r = null;
                    if (member_id != null && !member_id.equals("")) {
                        r = kamMemberResource.getUserListInfo("{member_id:" + seresult.get(i)[3] + "}", "1", "1");
                    } else {
                        r = kamMemberResource.getUserListInfo("{organization_id:" + seresult.get(i)[4] + "}", "1", "1");
                    }
                    KamMemberShowDTO km = (KamMemberShowDTO) r.getValues().get(0);
                    if (member_id != null && !member_id.equals("")) {
                        flowpath.setMember_name(km.getMember_name());

                    } else {
                        flowpath.setMember_name("所有成员");
                    }

                    flowpath.setKamMemberShowDTOs((ArrayList<KamMemberShowDTO>) r.getValues());
                    flowpath.setOrganization_name(km.getOrganization_name());

                    if (nopass != null && !nopass.equals("")) {
                        List<FlowPathShowDTO> fps = getPassInfo("{not_pass:" + nopass + "}", "1", "1");
                        if (fps != null && fps.size() > 0) {
                            FlowPathShowDTO fs = (FlowPathShowDTO) getPassInfo("{flow_path_id:"+nopass+"}", "1", "1").get(0);
                            flowpath.setFs(fs);
                        }
                    }
                    result.add(flowpath);
                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion("调用成功");
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("调用失败");
            }
            resultDTO.setValues(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    /**
     * 修改not_pass
     *
     * @param not_pass
     * @param size
     * @param page
     * @return
     */
    public List<FlowPathShowDTO> getPassInfo(String not_pass, String size, String page) {


        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(not_pass);
            String existName = "0";

            String sqlexit = "select count(1) from flow_path where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

            if (json.has("flow_path_id")) {
                sql_w += " AND flow_path_id = '" + json.getString("flow_path_id") + "'";
            }
            if (json.has("not_pass")) {
                sql_w += " AND not_pass = '" + json.getString("not_pass") + "'";
            }


            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<FlowPathShowDTO> result = new ArrayList<FlowPathShowDTO>();
            if (!existName.equals("0")) {
                String sql = "select flow_path_id,apply_manage_id,member_id,organization_id,orderer,not_pass from flow_path where 1=1 " + sql_w + " ORDER BY orderer ASC" + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {

                    FlowPathShowDTO flowpath = new FlowPathShowDTO();
                    flowpath.setFlow_path_id(seresult.get(i)[1]);
                    flowpath.setApply_manage_id(seresult.get(i)[2]);
                    String member_id = seresult.get(i)[3];
                    flowpath.setMember_id(member_id);
                    flowpath.setOrganization_id(seresult.get(i)[4]);
                    flowpath.setOrderer(seresult.get(i)[5]);
                    String nopass = seresult.get(i)[6];
                    flowpath.setNot_pass(nopass);

                    ResultDTO r = null;
                    if (member_id != null && !member_id.equals("")) {
                        r = kamMemberResource.getUserListInfo("{member_id:" + seresult.get(i)[3] + "}", "1", "1");
                    } else {
                        r = kamMemberResource.getUserListInfo("{organization_id:" + seresult.get(i)[4] + "}", "1", "1");
                    }
                    KamMemberShowDTO km = (KamMemberShowDTO) r.getValues().get(0);
                    if (member_id != null && !member_id.equals("")) {
                        flowpath.setMember_name(km.getMember_name());

                    } else {
                        flowpath.setMember_name("所有成员");
                    }

                    flowpath.setKamMemberShowDTOs((ArrayList<KamMemberShowDTO>) r.getValues());
                    flowpath.setOrganization_name(km.getOrganization_name());

                    result.add(flowpath);


                }
            }


//            if (seresult.size() != 0) {
//                resultDTO.setStatus("90000");
//                resultDTO.setDescritpion("调用成功");
//            } else {
//                resultDTO.setStatus("90001");
//                resultDTO.setDescritpion("调用失败");
//            }
//            resultDTO.setValues(result);
            return result;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 查询到达某步流程前的数据
     *
     * @param select
     * @param page
     * @param size
     * @return
     */
    @Override
    public ResultDTO getPartFlowPathInfo(String select, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(select);
            String existName = "0";

            String sqlexit = "select count(1) from flow_path where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

            if (json.has("flow_path_id")) {
                sql_w += " AND flow_path_id = '" + json.getString("flow_path_id") + "'";
            }
            if (json.has("apply_manage_id")) {
                sql_w += " AND apply_manage_id = '" + json.getString("apply_manage_id") + "'";
            }

            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<FlowPathShowDTO> result = new ArrayList<FlowPathShowDTO>();
            if (!existName.equals("0")) {
                String sql = "select flow_path_id,apply_manage_id,member_id,organization_id,orderer from flow_path where 1=1 " + sql_w + " ORDER BY orderer ASC" + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                //for (int i = 0; i < seresult.size(); i++) {

                FlowPathShowDTO flowpath = new FlowPathShowDTO();
//                    flowpath.setFlow_path_id(seresult.get(i)[1]);
                flowpath.setApply_manage_id(seresult.get(0)[2]);
//                    String member_id = seresult.get(i)[3];
//                    flowpath.setMember_id(member_id);
//                    flowpath.setOrganization_id(seresult.get(i)[4]);
                flowpath.setOrderer(seresult.get(0)[5]);

                if (seresult.get(0)[5] != null && !seresult.get(0)[5].equals("")) {
                    String sql_all = "select flow_path_id,apply_manage_id,member_id,organization_id,orderer,not_pass from flow_path where orderer< '" + seresult.get(0)[5] + "' AND apply_manage_id = '" + seresult.get(0)[2] + "' ORDER BY orderer ASC" + sql_page;
                    List<String[]> seresults = this.getReportingTo(sql_all);
                    for (int j = 0; j < seresults.size(); j++) {

                        FlowPathShowDTO flow = new FlowPathShowDTO();
                        flow.setFlow_path_id(seresults.get(j)[1]);
                        flow.setApply_manage_id(seresults.get(j)[2]);
                        String member_id = seresults.get(j)[3];
                        flow.setMember_id(member_id);
                        flow.setOrganization_id(seresults.get(j)[4]);
                        flow.setOrderer(seresults.get(j)[5]);
                        flow.setNot_pass(seresults.get(j)[6]);
                        ResultDTO r = null;
                        if (member_id != null && !member_id.equals("")) {
                            r = kamMemberResource.getUserListInfo("{member_id:" + seresults.get(j)[3] + "}", "1", "1");
                        } else {
                            r = kamMemberResource.getUserListInfo("{organization_id:" + seresults.get(j)[4] + "}", "1", "1");
                        }

                        KamMemberShowDTO km = (KamMemberShowDTO) r.getValues().get(0);
                        if (member_id != null && !member_id.equals("")) {
                            flow.setMember_name(km.getMember_name());

                        } else {
                            flow.setMember_name("所有成员");
                        }
                        flow.setOrganization_name(flow.getMember_name() + " (" + km.getOrganization_name() + ")");
                        flow.setKamMemberShowDTOs((ArrayList<KamMemberShowDTO>) r.getValues());
                        result.add(flow);
                    }
                }

            }
            // }
            if (seresult.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion("流程查询成功！");
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("流程查询失败！");
            }
            resultDTO.setValues(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    /**
     * 添加
     *
     * @param flowPathPullDTO
     * @return
     */
    @Override
    public ResultDTO addFlowPathInfo(FlowPathPullDTO flowPathPullDTO) {

        int resultls = 0;

        ResultDTO resultDTO = new ResultDTO();

        try {
            //JSONObject json = new JSONObject();

            String maxOne = "";
            String sql_w = "";
            String sqlexit = "select count(1) from flow_path where 1=1 ";

//            String max = "Select max(order) from flow_path";
//            maxOne =getReportingToOne(max);
//            if(maxOne==null||maxOne.equals("")){
//                maxOne="0";
//            }
            //构建返回对象

            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

            if (null != flowPathPullDTO.getApply_manage_id() && !"".equals(flowPathPullDTO.getApply_manage_id())) {
                String apply_manage_id = flowPathPullDTO.getApply_manage_id();
                sql_w += " AND apply_manage_id = '" + apply_manage_id + "'";
                String max = "SELECT MAX(f.orderer) FROM flow_path AS f WHERE f.apply_manage_id='" + apply_manage_id + "'";
                maxOne = getReportingToOne(max);
                if (maxOne == null || maxOne.equals("")) {
                    maxOne = "0";
                }

            }
            if (null != flowPathPullDTO.getMember_id() && !"".equals(flowPathPullDTO.getMember_id())) {
                sql_w += " AND member_id = '" + flowPathPullDTO.getMember_id() + "'";
            }
            if (null != flowPathPullDTO.getOrganization_id() && !"".equals(flowPathPullDTO.getOrganization_id())) {
                sql_w += " AND organization_id = '" + flowPathPullDTO.getOrganization_id() + "'";
            }
            String existName = getReportingToOne(sqlexit + sql_w);

            if (!existName.equals("1")) {

                String meetingRoom_insert = "";
                meetingRoom_insert += "insert into flow_path(flow_path_id,apply_manage_id,member_id,organization_id,orderer)" +
                        "values ('" + uuid + "','" + flowPathPullDTO.getApply_manage_id() + "','" + flowPathPullDTO.getMember_id() + "'" +
                        ",'" + flowPathPullDTO.getOrganization_id() + "'" +
                        ",'" + (Integer.parseInt(maxOne) + 1) + "')";
                //插入业务表
                resultls = addReportingTo(meetingRoom_insert);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("该流程已经配置过");
                return resultDTO;
            }


            if (resultls != 0) {
                // resultDTO.setStr(uuid);
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion("流程配置成功");
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("流程配置失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultDTO;

    }

    /**
     * 修改信息
     *
     * @param flowPathPullDTO
     * @return
     */
    @Override
    public ResultDTO updateFlowPathInfo(FlowPathPullDTO flowPathPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

       try{
           String sql_w = "";
          // JSONObject json = new JSONObject();
           if (flowPathPullDTO.getApply_manage_id()!=null) {
               sql_w += " AND (apply_manage_id = '" + flowPathPullDTO.getApply_manage_id() + "'";
           }
           if (flowPathPullDTO.getMember_id()!=null) {
               sql_w += " or member_id = '" + flowPathPullDTO.getMember_id()+ "')";
           }

           String existFlow_path="";
           String sql_isHas = "select count(1) from flow_path WHERE flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'"+sql_w ;
           int resultls = 0;
           //构建返回对象

           if (!existFlow_path.equals("1")) {
               String flow_path = "";
               flow_path += "update flow_path set  ";
               if (null != flowPathPullDTO.getOrganization_id() && !"".equals(flowPathPullDTO.getOrganization_id())) {
                   flow_path += " organization_id='" + flowPathPullDTO.getOrganization_id() + "'";
               }
               if (null != flowPathPullDTO.getMember_id()) {
                   flow_path += ",member_id='" + flowPathPullDTO.getMember_id() + "'";
               }
               if (null != flowPathPullDTO.getApply_manage_id() && !"".equals(flowPathPullDTO.getApply_manage_id())) {
                   flow_path += " ,apply_manage_id='" + flowPathPullDTO.getApply_manage_id() + "'";
               }
               flow_path += " where flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'";
               //更新会议室表
               resultls = addReportingTo(flow_path);
           }
           if (resultls != 0) {
               resultDTO.setStatus("90000");
               resultDTO.setDescritpion("流程修改成功！");
           } else {
               resultDTO.setStatus("90001");
               resultDTO.setDescritpion("该流程已配置！");
           }

       } catch (Exception e) {
           e.printStackTrace();
       }
        return resultDTO;
    }

    /**
     * 删除
     *
     * @param flowPathPullDTO
     * @return
     */
    @Override
    public ResultDTO deleteFlowPathInfo(FlowPathPullDTO flowPathPullDTO) {


        /**
         * 先去修改orderer值
         */
        String maxOne = "";


        int rrr = 0;
        String max = "SELECT orderer FROM flow_path  WHERE flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'";

        maxOne = getReportingToOne(max);

        if (maxOne != null || !maxOne.equals("")) {

            String applyy = "";

            String apply = "select apply_manage_id from flow_path where flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'";

            applyy = getReportingToOne(apply);

            String update_sql = "update flow_path set orderer = orderer-1 where orderer > '" + maxOne + "' AND apply_manage_id ='" + applyy + "' ";

            rrr = this.addReportingTo(update_sql);
        }


        //删除之前查询该表是否有记录
        String sql = "select count(1) from flow_path where flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'";
        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (existName != null) {

            String QUERY = "";

            QUERY += "delete from flow_path where flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'";

            result = this.addReportingTo(QUERY);
        }


        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("调用成功，删除成功");


        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("调用失败，删除失败");
        }
        return resultDTO;
    }

    /**
     * g根据apply_manage_id删除全部此流程
     *
     * @param flowPathPullDTO
     * @return
     */
    @Override
    public ResultDTO deleteAllFlowPathInfo(FlowPathPullDTO flowPathPullDTO) {
        //删除之前查询该表是否有记录
        String sql = "select count(1) from flow_path where flow_path_id='" + flowPathPullDTO.getApply_manage_id() + "'";
        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (existName != null) {

            String QUERY = "";

            QUERY += "delete from flow_path where apply_manage_id='" + flowPathPullDTO.getApply_manage_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("流程删除成功！");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("流程删除失败！");
        }
        return resultDTO;
    }

    /**
     * 修改not_pass字段
     *
     * 添加不通过原因
     * @param flowPathPullDTO
     * @return
     */
    @Override
    public ResultDTO updateNotPassInfo(FlowPathPullDTO flowPathPullDTO) {

        String sql_isHas = "select count(1) from flow_path WHERE flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "' AND ";

        String existFlow_path = getReportingToOne(sql_isHas);

        int resultls = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        if (!existFlow_path.equals("")) {
            String flow_path = "";
            flow_path += "update flow_path set  ";
            if (null != flowPathPullDTO.getNot_pass() && !"".equals(flowPathPullDTO.getNot_pass())) {
                flow_path += " not_pass='" + flowPathPullDTO.getNot_pass() + "'";
            }
            flow_path += " where flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "'";
            //更新会议室表
            resultls = addReportingTo(flow_path);
        }
        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("修改成功！");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("修改失败！");
        }
        return resultDTO;
    }

    /**
     * 点击删除的时候，根据传进来的flow_path_id，apply_manage_id，修改not_pass的字段值为空
     * @param flowPathPullDTO
     * @return
     */
    @Override
    public ResultDTO deletenot_PassInfo(FlowPathPullDTO flowPathPullDTO) {
        String sql = "select count(1) from flow_path where flow_path_id='" + flowPathPullDTO.getFlow_path_id() + "' AND apply_manage_id='" + flowPathPullDTO.getApply_manage_id() + "'";
        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (existName != null) {

            String QUERY = "";

            QUERY += "delete flow_path set not_pass='";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("流程删除成功！！");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("流程删除失败！！");
        }
        return resultDTO;
    }
}



